/*
 * ServiceLoad.java
 * 
 * This file is part of Netuno.
 * 
 * CajuScript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3, or (at your option) 
 * any later version.
 * 
 * CajuScript is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with CajuScript.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.netuno;

import java.net.Socket;
import org.apache.log4j.Logger;

/**
 * Services Loader.
 * @author eduveks
 */
public class ServiceLoad extends Thread {
    /**
     * Logger.
     */
    private static Logger logger = Logger.getLogger(ServiceLoad.class);
    /**
     * Client Socket.
     */
    private Socket clientSocket;
    /**
     * Service Load
     * @param client Client socket
     */
    public ServiceLoad(final Socket client) {
        clientSocket = client;
    }
    /**
     * Start service loading
     */
    @Override
    public final void run() {
        try {
            synchronized (this) {
                if (!Config.isStarting() && Config.getClientSocketTimeOut() > 0) {
                    clientSocket.setSoTimeout(Config.getClientSocketTimeOut());
                }
                if (!clientSocket.isConnected()) {
                    return;
                }
                if (!ServiceMonitor.isAllowNewConnections()) {
                    while (true) {
                        if (!ServiceMonitor.isAllowNewConnections()) {
                            Thread.sleep(100);
                            continue;
                        } else {
                            break;
                        }
                    }
                }
                logger.info("New client connected: "+ clientSocket.getInetAddress().getHostName());
                Service service;
                while (true) {
                    service = ServiceMonitor.getService();
                    if (service != null) {
                        break;
                    }
                    Thread.sleep(100);
                }
                service.setClient(clientSocket);
                service.go();
            }
        } catch (Exception e) {
            logger.error("Client socket error.", e);
        } finally {
            clientSocket = null;
        }
    }
}
